BCON147_MIDTERM_PROJECT_EXERCISE

BCon 147: special topics

Author

MA. AMOR C. LUMANTA

Published

October 22, 2024

1 Project overiew

In this project, we will explore employee attrition and performance using the HR Analytics Employee Attrition & Performance dataset. The primary goal is to develop insights into the factors that contribute to employee attrition. By analyzing a range of factors, including demographic data, job satisfaction, work-life balance, and job role, we aim to help businesses identify key areas where they can improve employee retention.

2 Scenario

Imagine you are working as a data analyst for a mid-sized company that is experiencing high employee turnover, especially among high-performing employees. The company has been facing increased costs related to hiring and training new employees, and management is concerned about the negative impact on productivity and morale. The human resources (HR) team has collected historical employee data and now looks to you for actionable insights. They want to understand why employees are leaving and how to retain talent effectively.

Your task is to analyze the dataset and provide insights that will help HR prioritize retention strategies. These strategies could include interventions like revising compensation policies, improving job satisfaction, or focusing on work-life balance initiatives. The success of your analysis could lead to significant cost savings for the company and an increase in employee engagement and performance.

3 Understanding data source

The dataset used for this project provides information about employee demographics, performance metrics, and various satisfaction ratings. The dataset is particularly useful for exploring how factors such as job satisfaction, work-life balance, and training opportunities influence employee performance and attrition.

This dataset is well-suited for conducting in-depth analysis of employee performance and retention, enabling us to build predictive models that identify the key drivers of employee attrition. Additionally, we can assess the impact of various organizational factors, such as training and work-life balance, on both performance and retention outcomes.

## datatable function from DT package create an HTML widget display of the dataset
## install DT package if the package is not yet available in your R environment
readxl::read_excel("dataset/dataset-variable-description.xlsx") |> 
  DT::datatable()

4 Data wrangling and management

Libraries

Task: Load the necessary libraries

Before we start working on the dataset, we need to load the necessary libraries that will be used for data wrangling, analysis and visualization. Make sure to load the following libraries here. For packages to be installed, you can use the install.packages function. There are packages to be installed later on this project, so make sure to install them as needed and load them here.

# load all your libraries here

#install.packages("magrittr")
library(magrittr)
#install.packages("dplyr")
library(dplyr)
#install.packages("tidyverse")
library(tidyverse)
#install.packages("ggplot2")
library(ggplot2)
#install.packages("readr")
library(readr)
#install.packages("DT")
library(DT)
#install.packages("janitor")
library(janitor)
#install.packages("GGally")
library(GGally)
#install.packages("sjPlot")
library(sjPlot)
#install.packages("report")
library(report)
#install.packages("ggstatsplot")
library(ggstatsplot)

4.1 Data importation

Task 4.1. Merging dataset
  • Import the two dataset Employee.csv and PerformanceRating.csv. Save the Employee.csv as employee_dta and PerformanceRating.csv as perf_rating_dta.

  • Merge the two dataset using the left_join function from dplyr. Use the EmployeeID variable as the varible to join by. You may read more information about the left_join function here.

  • Save the merged dataset as hr_perf_dta and display the dataset using the datatable function from DT package.

## import the two data here

employee_dta <- read_csv("dataset/Employee.csv")
perf_rating_dta <- read_csv("dataset/PerformanceRating.csv")

## merge employee_dta and perf_rating_dta using left_join function.
## save the merged dataset as hr_perf_dta

hr_perf_dta <- left_join(employee_dta, perf_rating_dta, by = "EmployeeID")

## Use the datatable from DT package to display the merged dataset

datatable(hr_perf_dta)

4.2 Data management

Task 4.2. Standardizing variable names
  • Using the clean_names function from janitor package, standardize the variable names by using the recommended naming of variables.

  • Save the renamed variables as hr_perf_dta to update the dataset.

## clean names using the janitor packages and save as hr_perf_dta
library(janitor)
hr_perf_dta <- hr_perf_dta %>% clean_names()

## display the renamed hr_perf_dta using datatable function

datatable(hr_perf_dta)
Task 4.2. Recode data entries
  • Create a new variable cat_education wherein education is 1 = No formal education; 2 = High school; 3 = Bachelor; 4 = Masters; 5 = Doctorate. Use the case_when function to accomplish this task.

  • Similarly, create new variables cat_envi_sat, cat_job_sat, and cat_relation_sat for environment_satisfaction, job_satisfaction, and relationship_satisfaction, respectively. Re-code the values accordingly as 1 = Very dissatisfied; 2 = Dissatisfied; 3 = Neutral; 4 = Satisfied; and 5 = Very satisfied.

  • Create new variables cat_work_life_balance, cat_self_rating, cat_manager_rating for work_life_balance, self_rating, and manager_rating, respectively. Re-code accordingly as 1 = Unacceptable; 2 = Needs improvement; 3 = Meets expectation; 4 = Exceeds expectation; and 5 = Above and beyond.

  • Create a new variable bi_attrition by transforming attrition variable as a numeric variabe. Re-code accordingly as No = 0, and Yes = 1.

  • Save all the changes in the hr_perf_dta. Note that saving the changes with the same name will update the dataset with the new variables created.

## create cat_education
str(hr_perf_dta)
spc_tbl_ [6,899 x 33] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
 $ employee_id                       : chr [1:6899] "3012-1A41" "3012-1A41" "3012-1A41" "3012-1A41" ...
 $ first_name                        : chr [1:6899] "Leonelle" "Leonelle" "Leonelle" "Leonelle" ...
 $ last_name                         : chr [1:6899] "Simco" "Simco" "Simco" "Simco" ...
 $ gender                            : chr [1:6899] "Female" "Female" "Female" "Female" ...
 $ age                               : num [1:6899] 30 30 30 30 30 30 30 30 30 38 ...
 $ business_travel                   : chr [1:6899] "Some Travel" "Some Travel" "Some Travel" "Some Travel" ...
 $ department                        : chr [1:6899] "Sales" "Sales" "Sales" "Sales" ...
 $ distance_from_home_km             : num [1:6899] 27 27 27 27 27 27 27 27 27 23 ...
 $ state                             : chr [1:6899] "IL" "IL" "IL" "IL" ...
 $ ethnicity                         : chr [1:6899] "White" "White" "White" "White" ...
 $ education                         : num [1:6899] 5 5 5 5 5 5 5 5 5 4 ...
 $ education_field                   : chr [1:6899] "Marketing" "Marketing" "Marketing" "Marketing" ...
 $ job_role                          : chr [1:6899] "Sales Executive" "Sales Executive" "Sales Executive" "Sales Executive" ...
 $ marital_status                    : chr [1:6899] "Divorced" "Divorced" "Divorced" "Divorced" ...
 $ salary                            : num [1:6899] 102059 102059 102059 102059 102059 ...
 $ stock_option_level                : num [1:6899] 1 1 1 1 1 1 1 1 1 0 ...
 $ over_time                         : chr [1:6899] "No" "No" "No" "No" ...
 $ hire_date                         : chr [1:6899] "03/01/2012" "03/01/2012" "03/01/2012" "03/01/2012" ...
 $ attrition                         : chr [1:6899] "No" "No" "No" "No" ...
 $ years_at_company                  : num [1:6899] 10 10 10 10 10 10 10 10 10 10 ...
 $ years_in_most_recent_role         : num [1:6899] 4 4 4 4 4 4 4 4 4 6 ...
 $ years_since_last_promotion        : num [1:6899] 9 9 9 9 9 9 9 9 9 10 ...
 $ years_with_curr_manager           : num [1:6899] 7 7 7 7 7 7 7 7 7 0 ...
 $ performance_id                    : chr [1:6899] "PR1295" "PR1908" "PR2617" "PR3436" ...
 $ review_date                       : chr [1:6899] "10/30/2016" "10/30/2017" "10/30/2018" "10/30/2019" ...
 $ environment_satisfaction          : num [1:6899] 3 4 5 1 3 3 4 4 5 3 ...
 $ job_satisfaction                  : num [1:6899] 3 4 5 3 4 2 5 2 5 3 ...
 $ relationship_satisfaction         : num [1:6899] 2 5 4 2 2 5 4 4 2 2 ...
 $ training_opportunities_within_year: num [1:6899] 3 3 3 3 1 1 1 1 2 2 ...
 $ training_opportunities_taken      : num [1:6899] 0 1 0 1 0 0 0 0 1 0 ...
 $ work_life_balance                 : num [1:6899] 4 2 4 3 3 3 4 2 5 5 ...
 $ self_rating                       : num [1:6899] 3 3 5 5 4 5 3 5 4 4 ...
 $ manager_rating                    : num [1:6899] 3 2 5 4 3 4 3 4 4 4 ...
 - attr(*, "spec")=
  .. cols(
  ..   EmployeeID = col_character(),
  ..   FirstName = col_character(),
  ..   LastName = col_character(),
  ..   Gender = col_character(),
  ..   Age = col_double(),
  ..   BusinessTravel = col_character(),
  ..   Department = col_character(),
  ..   `DistanceFromHome (KM)` = col_double(),
  ..   State = col_character(),
  ..   Ethnicity = col_character(),
  ..   Education = col_double(),
  ..   EducationField = col_character(),
  ..   JobRole = col_character(),
  ..   MaritalStatus = col_character(),
  ..   Salary = col_double(),
  ..   StockOptionLevel = col_double(),
  ..   OverTime = col_character(),
  ..   HireDate = col_character(),
  ..   Attrition = col_character(),
  ..   YearsAtCompany = col_double(),
  ..   YearsInMostRecentRole = col_double(),
  ..   YearsSinceLastPromotion = col_double(),
  ..   YearsWithCurrManager = col_double()
  .. )
 - attr(*, "problems")=<externalptr> 
colnames(hr_perf_dta)
 [1] "employee_id"                        "first_name"                        
 [3] "last_name"                          "gender"                            
 [5] "age"                                "business_travel"                   
 [7] "department"                         "distance_from_home_km"             
 [9] "state"                              "ethnicity"                         
[11] "education"                          "education_field"                   
[13] "job_role"                           "marital_status"                    
[15] "salary"                             "stock_option_level"                
[17] "over_time"                          "hire_date"                         
[19] "attrition"                          "years_at_company"                  
[21] "years_in_most_recent_role"          "years_since_last_promotion"        
[23] "years_with_curr_manager"            "performance_id"                    
[25] "review_date"                        "environment_satisfaction"          
[27] "job_satisfaction"                   "relationship_satisfaction"         
[29] "training_opportunities_within_year" "training_opportunities_taken"      
[31] "work_life_balance"                  "self_rating"                       
[33] "manager_rating"                    
library(dplyr)
hr_perf_dta <- hr_perf_dta %>%
  mutate(
    cat_education = case_when(
      education == "No formal education" ~ 1,
      education == "High school" ~ 2,
      education == "Bachelor" ~ 3,
      education == "Masters" ~ 4,
      education == "Doctorate" ~ 5,
      TRUE ~ NA_real_
    )
  )

## create cat_envi_sat,  cat_job_sat, and cat_relation_sat
hr_perf_dta <- hr_perf_dta %>%
  mutate(cat_envi_sat = case_when(
    environment_satisfaction == "Very dissatisfied" ~ 1,
    environment_satisfaction == "Dissatisfied" ~ 2,
    environment_satisfaction == "Neutral" ~ 3,
    environment_satisfaction== "Satisfied" ~ 4,
    environment_satisfaction == "Very satisfied" ~ 5
  ),
  cat_job_sat = case_when(
    job_satisfaction == "Very dissatisfied" ~ 1,
    job_satisfaction == "Dissatisfied" ~ 2,
    job_satisfaction == "Neutral" ~ 3,
    job_satisfaction == "Satisfied" ~ 4,
    job_satisfaction == "Very satisfied" ~ 5
  ),
  cat_relation_sat = case_when(
    relationship_satisfaction == "Very dissatisfied" ~ 1,
    relationship_satisfaction  == "Dissatisfied" ~ 2,
    relationship_satisfaction  == "Neutral" ~ 3,
    relationship_satisfaction  == "Satisfied" ~ 4,
    relationship_satisfaction  == "Very satisfied" ~ 5
  ))



## create cat_work_life_balance, cat_self_rating, and cat_manager_rating
hr_perf_dta <- hr_perf_dta %>%
  mutate(cat_work_life_balance = case_when(
    work_life_balance == "Unacceptable" ~ 1,
    work_life_balance == "Needs improvement" ~ 2,
    work_life_balance == "Meets expectation" ~ 3,
    work_life_balance == "Exceeds expectation" ~ 4,
    work_life_balance == "Above and beyond" ~ 5
  ),
  cat_self_rating = case_when(
    self_rating == "Unacceptable" ~ 1,
    self_rating  == "Needs improvement" ~ 2,
    self_rating == "Meets expectation" ~ 3,
    self_rating  == "Exceeds expectation" ~ 4,
    self_rating  == "Above and beyond" ~ 5
  ),
  cat_manager_rating = case_when(
    manager_rating == "Unacceptable" ~ 1,
    manager_rating == "Needs improvement" ~ 2,
    manager_rating == "Meets expectation" ~ 3,
    manager_rating == "Exceeds expectation" ~ 4,
    manager_rating == "Above and beyond" ~ 5
  ))

## create bi_attrition

hr_perf_dta <- hr_perf_dta %>%
  mutate(bi_attrition = case_when(
    attrition == "No" ~ 0,
    attrition == "Yes" ~ 1
  ))

## print the updated hr_perf_dta using datatable function

datatable(hr_perf_dta)

5 Exploratory data analysis

5.1 Descriptive statistics of employee attrition

Task 5.1. Breakdown of attrition by key variables
  • Select the variables attrition, job_role, department, age, salary, job_satisfaction, and work_life_balance. Save as attrition_key_var_dta.

  • Compute and plot the attrition rate across job_role, department, and age, salary, job_satisfaction, and work_life_balance. To compute for the attrition rate, group the dataset by job role. Afterward, you can use the count function to get the frequency of attrition for each job role and then divide it by the total number of observations. Save the computation as pct_attrition. Do not forget to ungroup before storing the output. Store the output as attrition_rate_job_role.

  • Plot for the attrition rate across job_role has been done for you! Study each line of code. You have the freedom to customize your plot accordingly. Show your creativity!

## selecting attrition key variables and save as `attrition_key_var_dta`

attrition_key_var_dta <- hr_perf_dta %>%
  select(attrition, job_role, department, age, salary,
         job_satisfaction, work_life_balance)

## compute the attrition rate across job_role and save as attrition_rate_job_role

hr_perf_dta <- hr_perf_dta %>%
  mutate(bi_attrition = case_when(
    attrition == "No" ~ 0,
    attrition == "Yes" ~ 1,
    TRUE ~ NA_real_  
  ))

attrition_key_var_dta <- hr_perf_dta %>%
  select(attrition, job_role, department, age, salary,
         job_satisfaction, work_life_balance, bi_attrition)
attrition_rate_job_role <- attrition_key_var_dta %>%
  group_by(job_role) %>%
  summarise(
    total = n(),  
    attrition_count = sum(bi_attrition, na.rm = TRUE) 
  ) %>%
  mutate(pct_attrition = (attrition_count / total) * 100) %>%
  ungroup()

## print attrition_rate_job_role

print(attrition_rate_job_role)
# A tibble: 13 x 4
   job_role                  total attrition_count pct_attrition
   <chr>                     <int>           <dbl>         <dbl>
 1 Analytics Manager           213              28         13.1 
 2 Data Scientist             1387             597         43.0 
 3 Engineering Manager         307              18          5.86
 4 HR Business Partner          25               0          0   
 5 HR Executive                119              29         24.4 
 6 HR Manager                   17               0          0   
 7 Machine Learning Engineer   582              95         16.3 
 8 Manager                     145              19         13.1 
 9 Recruiter                   152              86         56.6 
10 Sales Executive            1567             543         34.7 
11 Sales Representative        500             317         63.4 
12 Senior Software Engineer    512              84         16.4 
13 Software Engineer          1373             445         32.4 
## Plot the attrition rate

ggplot(attrition_rate_job_role, aes(x = reorder(job_role, -pct_attrition), y = pct_attrition, fill = job_role)) +
  geom_bar(stat = "identity", color = "black", fill = "yellow") +
  labs(
    title = "Attrition Rate by Job Role",
    x = "Job Role",
    y = "Attrition Rate (%)"
  ) +
  theme(
    panel.background = element_rect(fill = "black"),  
    plot.background = element_rect(fill = "black"),   
    panel.grid.major = element_line(color = "gray"),  
    panel.grid.minor = element_blank(),               
    axis.text.x = element_text(angle = 45, hjust = 1, color = "hotpink", size = 10),  
    axis.text.y = element_text(color = "white", size = 10),                         
    axis.title.x = element_text(color = "white", size = 12, face = "bold"),         
    axis.title.y = element_text(color = "white", size = 12, face = "bold"),         
    plot.title = element_text(color = "white", size = 14, face = "bold", hjust = 0.5),  
    legend.position = "none"  
  )

5.2 Identifying attrition key drivers using correlation analysis

Task 5.2. Conduct a correlation analysis to identify key drivers
  • Conduct a correlation analysis of key variables: bi_attrition, salary, years_at_company, job_satisfaction, manager_rating, and work_life_balance. Use the cor() function to run the correlation analysis. Remove missing values using the na.omit() before running the correlation analysis. Save the output in hr_corr.

  • Use a correlation matrix or heatmap to visualize the relationship between these variables and attrition. You can use the GGally package and use the ggcorr function to visualize the correlation heatmap. You may explore this site for more information: ggcorr.

  • Discuss which factors seem most correlated with attrition and what that suggests aobut why employees are leaving.

## conduct correlation of key variables. 
key_vars_dta <- hr_perf_dta %>%
  select(bi_attrition, salary, years_at_company, job_satisfaction, manager_rating, work_life_balance) %>%
  na.omit() 

hr_corr <- cor(key_vars_dta)

## print hr_corr 

print(hr_corr)
                  bi_attrition       salary years_at_company job_satisfaction
bi_attrition       1.000000000 -0.211181478    -0.6896527798     0.0132368129
salary            -0.211181478  1.000000000     0.2206442116     0.0053054850
years_at_company  -0.689652780  0.220644212     1.0000000000     0.0008700583
job_satisfaction   0.013236813  0.005305485     0.0008700583     1.0000000000
manager_rating    -0.007654429 -0.001596736     0.0178656879    -0.0158205481
work_life_balance  0.003428836 -0.001517145     0.0079339508     0.0417242942
                  manager_rating work_life_balance
bi_attrition        -0.007654429       0.003428836
salary              -0.001596736      -0.001517145
years_at_company     0.017865688       0.007933951
job_satisfaction    -0.015820548       0.041724294
manager_rating       1.000000000       0.007996938
work_life_balance    0.007996938       1.000000000
## install GGally package and use ggcorr function to visualize the correlation
ggcorr(key_vars_dta, label = TRUE, label_size = 3, hjust = 0.75, size = 3, palette = "RdBu", layout.exp = 2) +
  labs(title = "Correlation Heatmap of Attrition and Key Variables")

::::::::::: callout-note ## Discussion:

Provide your discussion here. :::Factors highly correlated with bi_attrition are likely to suggest drivers for employee attrition.For example, if work_life_balance or job_satisfaction has a strong negative correlation with bi_attrition, it might indicate that poor satisfaction or work-life balance is driving employees to leave.

5.3 Predictive modeling for attrition

Task 5.3. Predictive modeling for attrition
  • Create a logistic regression model to predict employee attrition using the following variables: salary, years_at_company, job_satisfaction, manager_rating, and work_life_balance. Save the model as hr_attrition_glm_model. Print the summary of the model using the summary function.

  • Install the sjPlot package and use the tab_model function to display the summary of the model. You may read the documentation here on how to customize your model summary.

  • Also, use the plot_model function to visualize the model coefficients. You may read the documentation here on how to customize your model visualization.

  • Discuss the results of the logistic regression model and what they suggest about the factors that contribute to employee attrition.

## run a logistic regression model to predict employee attrition
## save the model as hr_attrition_glm_model

hr_attrition_glm_model <- glm(
  bi_attrition ~ salary + years_at_company + job_satisfaction + manager_rating + work_life_balance,
  data = hr_perf_dta,
  family = binomial 
)

## print the summary of the model using the summary function

summary(hr_attrition_glm_model)

Call:
glm(formula = bi_attrition ~ salary + years_at_company + job_satisfaction + 
    manager_rating + work_life_balance, family = binomial, data = hr_perf_dta)

Coefficients:
                    Estimate Std. Error z value Pr(>|z|)    
(Intercept)        2.571e+00  2.173e-01  11.831   <2e-16 ***
salary            -3.633e-06  4.086e-07  -8.893   <2e-16 ***
years_at_company  -6.333e-01  1.476e-02 -42.919   <2e-16 ***
job_satisfaction   3.470e-02  3.186e-02   1.089    0.276    
manager_rating     5.071e-03  3.810e-02   0.133    0.894    
work_life_balance  2.587e-02  3.198e-02   0.809    0.419    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 8574.5  on 6708  degrees of freedom
Residual deviance: 4781.6  on 6703  degrees of freedom
  (190 observations deleted due to missingness)
AIC: 4793.6

Number of Fisher Scoring iterations: 5
## install sjPlot package and use tab_model function to display the summary of the model

tab_model(hr_attrition_glm_model, show.ci = TRUE, show.p = TRUE, show.se = TRUE, title = "Logistic Regression Model for Attrition")
Logistic Regression Model for Attrition
  bi attrition
Predictors Odds Ratios std. Error CI p
(Intercept) 13.08 2.84 0.00 – Inf <0.001
salary 1.00 0.00 0.00 – Inf <0.001
years at company 0.53 0.01 0.00 – Inf <0.001
job satisfaction 1.04 0.03 0.00 – Inf 0.276
manager rating 1.01 0.04 0.00 – Inf 0.894
work life balance 1.03 0.03 0.00 – Inf 0.419
Observations 6709
R2 Tjur 0.502
## use plot_model function to visualize the model coefficients

plot_model(hr_attrition_glm_model, show.values = TRUE, title = "Coefficients of Attrition Logistic Regression Model", colors = "navy")

::::::::: callout-note ## Discussion:

Provide your discussion here. :::Coefficients: Look at the sign of the coefficients (positive or negative). A positive coefficient suggests that as the predictor increases, the likelihood of attrition also increases. A negative coefficient indicates that as the predictor increases, the likelihood of attrition decreases.P-values: P-values help identify significant predictors. A small p-value (typically <0.05) suggests that the predictor is statistically significant in predicting employee attrition.Odds Ratios (Exp(Coefficient)): If you want to interpret the coefficients as odds ratios, you can exponentiate the coefficients using exp(coef(hr_attrition_glm_model)).

5.4 Analysis of compensation and turnover

Task 5.4. Analyzing compensation and turnover
  • Compare the average monthly income of employees who left the company (bi_attrition = 1) and those who stayed (bi_attrition = 0). Use the t.test function to conduct a t-test and determine if there is a significant difference in average monthly income between the two groups. Save the results in a variable called attrition_ttest_results.

  • Install the report package and use the report function to generate a report of the t-test results.

  • Install the ggstatsplot package and use the ggbetweenstats function to visualize the distribution of monthly income for employees who left and those who stayed. Make sure to map the bi_attrition variable to the x argument and the salary variable to the y argument.

  • Visualize the salary variable for employees who left and those who stayed using geom_histogram with geom_freqpoly. Make sure to facet the plot by the bi_attrition variable and apply alpha on the histogram plot.

  • Provide recommendations on whether revising compensation policies could be an effective retention strategy.

## compare the average monthly income of employees who left and those who stayed
attrition_ttest_results <- t.test(salary ~ bi_attrition, data = hr_perf_dta)


## print the results of the t-test

print(attrition_ttest_results)

    Welch Two Sample t-test

data:  salary by bi_attrition
t = 18.869, df = 5524.2, p-value < 2.2e-16
alternative hypothesis: true difference in means between group 0 and group 1 is not equal to 0
95 percent confidence interval:
 38577.82 47523.18
sample estimates:
mean in group 0 mean in group 1 
      125007.26        81956.76 
## install the report package and use the report function to generate a report of the t-test results

attrition_ttest_results <- t.test(salary ~ bi_attrition, data = hr_perf_dta)

# Generate a report of the t-test results

report(attrition_ttest_results)
Effect sizes were labelled following Cohen's (1988) recommendations.

The Welch Two Sample t-test testing the difference of salary by bi_attrition
(mean in group 0 = 1.25e+05, mean in group 1 = 81956.76) suggests that the
effect is positive, statistically significant, and medium (difference =
43050.50, 95% CI [38577.82, 47523.18], t(5524.24) = 18.87, p < .001; Cohen's d
= 0.51, 95% CI [0.45, 0.56])
# install ggstatsplot package and use ggbetweenstats function to visualize the distribution of monthly income for employees who left and those who stayed
 

ggbetweenstats(
  data = hr_perf_dta,
  x = bi_attrition,
  y = salary,
  title = "Distribution of Monthly Income by Attrition Status",
  x.label = "Attrition Status",
  y.label = "Monthly Salary",
  ggtheme = ggplot2::theme_minimal(), 
  pairwise.display = "p-adj"  
)

# create histogram and frequency polygon of salary for employees who left and those who stayed


ggplot(hr_perf_dta, aes(x = salary, fill = as.factor(bi_attrition))) +
  geom_histogram(alpha = 0.7, position = "identity", bins = 30, color = "white") +
  geom_freqpoly(aes(color = as.factor(bi_attrition)), size = 1.5, bins = 30) +
  facet_wrap(~ bi_attrition, labeller = as_labeller(c("0" = "Stayed", "1" = "Left"))) +
  labs(
    title = "Salary Distribution by Attrition Status",
    subtitle = "Comparing Employees Who Stayed vs. Left",
    x = "Monthly Salary",
    y = "Count",
    fill = "Attrition Status",
    color = "Attrition Status"
  ) +
  scale_fill_manual(values = c("#4DAF4A", "#E41A1C")) +  # Custom fill colors
  scale_color_manual(values = c("#377EB8", "#FF7F00")) +  # Custom line colors
  theme_minimal(base_size = 15) +  # Increase base font size
  theme(
    plot.title = element_text(size = 20, face = "bold", hjust = 0.5),
    plot.subtitle = element_text(size = 16, hjust = 0.5),
    strip.text = element_text(size = 14, face = "bold"),
    legend.position = "top",
    panel.grid.major = element_line(color = "gray90", size = 0.5),
    panel.grid.minor = element_blank()
  )

::: callout-note ## Discussion:

Provide your discussion here. :::If the t-test indicates a significant difference in salary between those who left and those who stayed, this may suggest that compensation is a significant factor in employee retention.If employees who left had significantly lower salaries, it could be beneficial to review and possibly revise compensation policies to ensure they are competitive and equitable.Implementing regular salary reviews and ensuring alignment with industry standards can help improve employee satisfaction and reduce turnover.

5.5 Employee satisfaction and performance analysis

Task 5.5. Analyzing employee satisfaction and performance
  • Analyze the average performance ratings (both ManagerRating and SelfRating) of employees who left vs. those who stayed. Use the group_by and count functions to calculate the average performance ratings for each group.

  • Visualize the distribution of SelfRating for employees who left and those who stayed using a bar plot. Use the ggplot function to create the plot and map the SelfRating variable to the x argument and the bi_attrition variable to the fill argument.

  • Similarly, visualize the distribution of ManagerRating for employees who left and those who stayed using a bar plot. Make sure to map the ManagerRating variable to the x argument and the bi_attrition variable to the fill argument.

  • Create a boxplot of salary by job_satisfaction and bi_attrition to analyze the relationship between salary, job satisfaction, and attrition. Use the geom_boxplot function to create the plot and map the salary variable to the x argument, the job_satisfaction variable to the y argument, and the bi_attrition variable to the fill argument. You need to transform the job_satisfaction and bi_attrition variables into factors before creating the plot or within the ggplot function.

  • Discuss the results of the analysis and provide recommendations for HR interventions based on the findings.

# Analyze the average performance ratings (both ManagerRating and SelfRating) of employees who left vs. those who stayed.

avg_self_rating <- hr_perf_dta %>%
  group_by(bi_attrition) %>%
  summarise(avg_self_rating = mean(self_rating, na.rm = TRUE))

# Print the result
avg_self_rating
# A tibble: 2 x 2
  bi_attrition avg_self_rating
         <dbl>           <dbl>
1            0            3.98
2            1            3.99
avg_manager_rating <- hr_perf_dta %>%
  group_by(bi_attrition) %>%
  summarise(avg_manager_rating = mean(manager_rating, na.rm = TRUE))

# Print the result
avg_manager_rating
# A tibble: 2 x 2
  bi_attrition avg_manager_rating
         <dbl>              <dbl>
1            0               3.48
2            1               3.46
hr_perf_sample <- hr_perf_dta %>% sample_n(1000)

# Group by bi_attrition and calculate average performance ratings
average_ratings <- hr_perf_dta %>%
  group_by(bi_attrition) %>%
  summarise(
    avg_self_rating = mean(self_rating, na.rm = TRUE),
    avg_manager_rating = mean(manager_rating, na.rm = TRUE)
  )

# Print the result
average_ratings
# A tibble: 2 x 3
  bi_attrition avg_self_rating avg_manager_rating
         <dbl>           <dbl>              <dbl>
1            0            3.98               3.48
2            1            3.99               3.46
# Visualize the distribution of SelfRating for employees who left and those who stayed using a bar plot.

ggplot(hr_perf_dta, aes(x = as.factor(self_rating), fill = as.factor(bi_attrition))) +
  geom_bar(position = "dodge", alpha = 0.7) +
  labs(
    title = "Distribution of Self-Rating by Attrition Status",
    x = "Self Rating",
    y = "Count",
    fill = "Attrition Status"
  ) +
  scale_fill_manual(values = c("black", "navyblue")) +  
  theme_minimal(base_size = 15) +
  theme(
    plot.title = element_text(size = 20, face = "bold", hjust = 0.5),
    legend.position = "top"
  )

# Visualize the distribution of ManagerRating for employees who left and those who stayed using a bar plot.

ggplot(hr_perf_dta, aes(x = as.factor(manager_rating), fill = as.factor(bi_attrition))) +
  geom_bar(position = "dodge", alpha = 0.7) +
  labs(
    title = "Distribution of Manager-Rating by Attrition Status",
    x = "Manager Rating",
    y = "Count",
    fill = "Attrition Status"
  ) +
  scale_fill_manual(values = c("purple", "hotpink")) +  
  theme_minimal(base_size = 15) +
  theme(
    plot.title = element_text(size = 20, face = "bold", hjust = 0.5),
    legend.position = "below"
  )

# create a boxplot of salary by job_satisfaction and bi_attrition to analyze the relationship between salary, job satisfaction, and attrition.

hr_perf_dta$job_satisfaction <- as.factor(hr_perf_dta$job_satisfaction)
hr_perf_dta$bi_attrition <- as.factor(hr_perf_dta$bi_attrition)

ggplot(hr_perf_dta, aes(x = job_satisfaction, y = salary, fill = bi_attrition)) +
  geom_boxplot(alpha = 0.7) +
  labs(
    title = "Salary Distribution by Job Satisfaction and Attrition Status",
    x = "Job Satisfaction",
    y = "Salary",
    fill = "Attrition Status"
  ) +
  scale_fill_manual(values = c("yellow", "lightblue")) +  
  theme_minimal(base_size = 15) +
  theme(
    plot.title = element_text(size = 20, face = "bold", hjust = 0.5),
    legend.position = "top"
  )

::: callout-note ## Discussion:

Provide your discussion here. :::For the performance ratings the analysis shows how employees who left have different average self and manager ratings compared to those who stayed. If there is a significant difference in these ratings, HR may consider coaching or management interventions to improve satisfaction. For the salary and job satisfaction the boxplot shows that employees with lower job satisfaction or those with lower salary tend to leave, HR could focus on salary adjustments or satisfaction-based programs to retain talent.

5.6 Work-life balance and retention strategies

::: callout-tip ## Task 5.6. Analyzing work-life balance and retention strategies

At this point, you are already well aware of the dataset and the possible factors that contribute to employee attrition. Using your R skills, accomplish the following tasks:

  • Analyze the distribution of WorkLifeBalance ratings for employees who left versus those who stayed.
work_life_balance_distribution <- hr_perf_dta %>%
  group_by(bi_attrition) %>%
  summarise(
    count = n(),
    avg_work_life_balance = mean(work_life_balance, na.rm = TRUE),
    sd_work_life_balance = sd(work_life_balance, na.rm = TRUE)
  )

# Print the distribution results
work_life_balance_distribution
# A tibble: 2 x 4
  bi_attrition count avg_work_life_balance sd_work_life_balance
  <fct>        <int>                 <dbl>                <dbl>
1 0             4638                  3.41                 1.15
2 1             2261                  3.42                 1.14
  • Use visualizations to show the differences.
ggplot(hr_perf_dta, aes(x = factor(work_life_balance), fill = as.factor(bi_attrition))) +
  geom_bar(position = "dodge") +
  labs(
    title = "Distribution of Work-Life Balance Ratings by Attrition Status",
    x = "Work-Life Balance Rating",
    y = "Count",
    fill = "Attrition Status"
  ) +
  scale_fill_manual(values = c("limegreen", "black")) + 
  theme_minimal(base_size = 15) +
  theme(
    plot.title = element_text(size = 20, face = "bold"),
    legend.position = "top"
  )

  • Assess whether employees with poor work-life balance are more likely to leave.
work_life_balance_ttest <- t.test(work_life_balance ~ bi_attrition, data = hr_perf_dta)

# Print t-test results
work_life_balance_ttest

    Welch Two Sample t-test

data:  work_life_balance by bi_attrition
t = -0.28121, df = 4562.3, p-value = 0.7786
alternative hypothesis: true difference in means between group 0 and group 1 is not equal to 0
95 percent confidence interval:
 -0.06614473  0.04954960
sample estimates:
mean in group 0 mean in group 1 
       3.411871        3.420168 

You have the freedom how you will accomplish this task. Be creative and provide insights that will help HR develop effective retention strategies. :::Identify Critical Ratings- If employees who left reported significantly lower work-life balance ratings, this suggests that work-life balance is a critical factor in attrition.Flexible Work Arrangements- Implement flexible working hours or remote work options to help employees manage their work-life balance better.Work-Life Balance Programs- Consider introducing wellness programs that encourage healthy work-life balance practices, such as mindfulness training, fitness classes, and time-off policies.Regular Feedback- Conduct regular employee surveys to assess work-life balance perceptions and address concerns promptly.Management Training: Train managers to recognize signs of employee burnout and promote work-life balance within their teams.

5.7 Recommendations for HR interventions

::: callout-tip ## Task 5.7. Recommendations for HR interventions

Based on the analysis conducted, provide recommendations for HR interventions that could help reduce employee attrition and improve overall employee satisfaction and performance. You may use the following question as guide for your recommendations and discussions.

  • What are the key factors contributing to employee attrition in the company? ::: The analysis revealed that compensation, job satisfaction, and work-life balance are critical factors influencing employee attrition. Employees with lower salaries and poor job satisfaction ratings were significantly more likely to leave the company.

  • Which factors are most strongly correlated with attrition? :::Salary showed a strong negative correlation with attrition, indicating that competitive compensation is essential for retention. Also job satisfaction and work-life balance were positively correlated with retention, highlighting their importance in employee satisfaction.

  • What strategies could be implemented to improve employee retention and satisfaction? :::HR should implement competitive compensation packages and enhance job satisfaction through feedback mechanisms and career development opportunities and promoting work-life balance through flexible work options and wellness programs can significantly improve employee retention.

  • How can HR leverage the insights from the analysis to develop effective retention strategies? :::HR can use data-driven insights to create targeted interventions aimed at reducing attrition in critical areas identified in the analysis. Tailoring programs to address specific employee segments will ensure that interventions are relevant and effective.

  • What are the potential benefits of implementing these strategies for the company? :::Reduced Turnover Costs: By decreasing attrition rates, the company can save on recruitment, onboarding, and training expenses associated with new hires. :::Improved Employee Morale: Satisfied employees are likely to be more engaged and motivated, leading to enhanced productivity and performance. :::Stronger Employer Brand: Positive workplace culture and low turnover rates can help attract top talent, enhancing the company’s reputation in the job market. :::Long-term Growth: Implementing effective retention strategies fosters loyalty among employees, which can contribute to the company’s long-term success and stability.